<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    function getCode(time){
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          Math.random() > 0.1 ? resolve(time + 'success') : reject('fail')
        }, time * 1000)
      })
    }

    // const code = getCode();
    // code.then((res) => {
    //   console.log('第一个getcode', res)
    //   return getCode()
    // }).then((res) => {
    //   console.log('第二个getcode', res)
    // }).catch(err => {
    //   console.log('catch', err);
    // }).finally(() => {
    //   console.log('finally')
    // })
    Promise.myAll = function(promises){
      if(Array.isArray(promises)){
        // 返回一个新的promise
        return new Promise((resolve, reject) => {
          // 遍历数组
          // 所有的promise对象全部成功之后在调用resolve
          // 只要有一个失败调用reject
          let startPromiseNum = 0;
          let promiseResult = [];
          promises.forEach((promise, i) => {
            if(promise instanceof Promise){
              promise.then(res => {
                // 当前一个promise成功
                promiseResult[i] = res;
                startPromiseNum++;
                // 所有的promise执行成功
                if(startPromiseNum === promises.length){
                  resolve(promiseResult);
                }
              }, (err) => {
                reject(err)
              })
            } else {
              throw new Error('参数必须是Promise')
            }
          })
        })
      } else {
        throw new Error('参数必须是数组')
      }
    }
    Promise.myAll([getCode(10), getCode(3), getCode(5)]).then(res => {
      console.log('res', res);
    }).catch(err => {
      console.log(err);
    })
  </script>
</body>
</html>